<script lang="ts" setup>

import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { tryLipstick } from '@/api/system/index'

import type { UploadProps } from 'element-plus'
import Compressor from 'compressorjs';
const imageUrl = ref('')
const base64Data = ref('' as any)
const resUrl = ref('' as any)
const color = ref('')
const baseUrl = import.meta.env.VITE_VUE_APP_BASE_URL;
const loading_upload = ref(false)
const loading_creat = ref(false)

const predefineColors = ref([
    '#ff4500',
    '#ff8c00',
    '#ffd700',
    '#90ee90',
    '#00ced1',
    '#1e90ff',
    '#c71585',
    'rgba(255, 69, 0, 0.68)',
    'rgb(255, 120, 0)',
    'hsv(51, 100, 98)',
    'hsva(120, 40, 94, 0.5)',
    'hsl(181, 100%, 37%)',
    'hsla(209, 100%, 56%, 0.73)',
    '#c7158577',
])

//压缩图片
const handleFileUploadWithCompressor = (event: any) => {
    const file = event.target.files[0];
    new Compressor(file, {
        quality: 0.7, // 压缩质量
        width: 800, // 最大宽度
        height: 600, // 最大高度
        success(result) {
            // result是压缩后的文件对象，可以进行上传操作
            console.log('压缩后的文件:', result);
        },
        error(err) {
            console.log('压缩出错:', err);
        }
    });
}


//生成结果图
const creatImage = async () => {
    if (!imageUrl.value) {
        ElMessage({ message: '请上传图片', type: "error" });
        return
    }

    if (!color.value) {
        ElMessage({ message: '请选择唇色', type: "error" });
        return
    }
    loading_creat.value = true
    let data = {
        imageUrl: imageUrl.value,
        LipColorInfos: [getColorParams(color.value)]
    }
    try {
        let res = await tryLipstick(data)
        resUrl.value = res.data.ResultUrl
        loading_creat.value = false
    } catch (err) {
        loading_creat.value = false

    }
}

//获取color参数
function getColorParams(rgbaStr: any) {
    console.log()
    // 使用正则表达式提取rgba中的各个数值
    const rgbaValues = rgbaStr.match(/\d+/g).map(Number);
    const r = rgbaValues[0];
    const g = rgbaValues[1];
    const b = rgbaValues[2];
    const a = rgbaValues[3] * 100;

    // 这里进行具体的转换操作，示例中简单做了些数值调整，你可按实际要求改
    const convertedR = r;
    const convertedG = g;
    const convertedB = b;
    const convertedA = a;

    return {
        RGBA: {
            R: convertedR,
            G: convertedG,
            B: convertedB,
            A: convertedA
        },
        ModelAlpha: convertedA
    };
}


const handleAvatarSuccess = (res: any) => {
    imageUrl.value = res.data
    loading_upload.value = false
}

const beforeAvatarUpload = (rawFile: any) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('必须是jpg或png格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('图片不能大于10MB')
        return false
    }
    loading_upload.value = true
    const targetSize = 0.5 * 1024 * 1024; // 目标大小为0.5M，单位换算为字节
    const qualityEstimate = targetSize / rawFile.size > 1 ? 1 : targetSize / rawFile.size; // 预估quality值

    console.log('当前图片大小', (rawFile.size / 1024).toFixed(0) + 'KB')
    console.log('压缩倍率', qualityEstimate)

    //分辨率最大为2000 
    return new Promise((resolve, reject) => {
        // 使用Compressor进行图片压缩
        new Compressor(rawFile, {
            quality: qualityEstimate, // 压缩质量，可根据需求调整
            width: 1500,
            height: 1500,
            success(result) {
                // 压缩成功后，将压缩后的文件作为要上传的文件
                console.log('图片压缩成功,当前大小：', (result.size / 1024).toFixed(0) + 'KB')
                resolve(result);
            },
            error(err) {
                ElMessage.error('图片压缩出错：' + err.message);
                reject(err);
            }
        });
    })
}
// const beforeAvatarUpload = (rawFile: any) => {
//     if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
//         ElMessage.error('必须是jpg或png格式');
//         return false;
//     } else if (rawFile.size / 1024 / 1024 > 10) {
//         ElMessage.error('图片不能大于10MB');
//         return false;
//     }
//     loading_upload.value = true;

//     return new Promise((resolve, reject) => {
//         const targetSize = 1 * 1024 * 1024; // 目标大小为1M，单位换算为字节
//         const qualityEstimate = targetSize / rawFile.size; // 初始预估quality值
//         console.log('当前图片大小', rawFile.size / 1024 + 'KB')
//         console.log('压缩倍率',qualityEstimate);
//         let currentQuality = qualityEstimate;
//         const adjustQuality = (file: any, currentQuality: any) => {
//             return new Promise((innerResolve, innerReject) => {
//                 new Compressor(file, {
//                     quality: currentQuality,
//                     success(result) {
//                         const size = result.size; // 获取压缩后文件大小，这里假设Compressor压缩后的文件有size属性来表示大小，若实际没有需调整获取方式
//                         console.log('当前压缩文件大小：', size / 1024 + 'KB');
//                         if (size > targetSize) {
//                             // 文件太大，适当降低quality，这里采用每次乘以0.8的线性调整策略，可根据实际情况调整系数
//                             const newQuality = currentQuality * 0.8;
//                             if (newQuality < 0.01) {
//                                 // 当quality过低时，直接返回当前结果，避免陷入死循环或过度压缩导致图片质量太差
//                                 innerResolve(result);
//                             } else {
//                                 adjustQuality(file, newQuality).then(innerResolve).catch(innerReject);
//                             }
//                         } else {
//                             innerResolve(result);
//                         }
//                     },
//                     error(err) {
//                         ElMessage.error('图片压缩出错：' + err.message);
//                         innerReject(err);
//                     }
//                 });
//             });
//         };
//         adjustQuality(rawFile, currentQuality).then(resolve).catch(reject);
//     });
// }
</script>
<template>
    <div style="display: flex;justify-content: center; flex-direction: column;align-items: center;">
        <el-divider>
            <el-icon style="color: #409eff;">
                <UploadFilled />
            </el-icon>
            STEP1 上传脸部图片
        </el-divider>
        <el-upload class="avatar-uploader" :action="baseUrl + 'system/upload/upload'" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" v-loading="loading_upload"
            element-loading-text="上传中...">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="object-fit: contain;" />
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
        <el-divider>
            <el-icon style="color: red;">
                <StarFilled />
            </el-icon>
            STEP2 选择唇色
        </el-divider>
        <el-color-picker v-model="color" show-alpha :predefine="predefineColors" />
        <el-divider>
            <el-icon style="color: green;">
                <Promotion />
            </el-icon>
            STEP3 生成图片
        </el-divider>

        <el-button color="green" @click="creatImage" :loading="loading_creat">生成图片</el-button>

        <div v-loading="loading_creat" element-loading-text="生成中..." style="padding: 5px;">

            <div class="resImage">
                <el-image v-if="resUrl" style="object-fit: contain;width: 178px;height: 178px;" :src="resUrl"
                    :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[resUrl]" :initial-index="4"
                    fit="contain" />
                <div v-else
                    style="width: 178px;height: 178px;display: flex;justify-content: center;align-items: center;color:#606266 ;;">
                    图片待生成~ </div>
            </div>
        </div>

    </div>
</template>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #606266;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.resImage {
    margin-top: 20px;
    width: 178px;
    height: 178px;
    color: black;
    border: 1px dashed #606266;
    border-radius: 6px;
}
</style>
<style>
.el-color-picker {
    width: 150px;
}

.el-color-picker__trigger {
    width: 150px;
}
</style>